import React, {Component} from 'react'
import {Button, FormControl, Pagination, Radio, Table, Popconfirm, Icon} from 'tinper-bee'
import {getWorkQualityDateUrl, getWorkQualityDeleteDateUrl} from '../WorkType/worktype.config'
import {addWorktpl, queryWorktpl, toggleStatus, referCheck} from './workquality.config'
import './index.less'
import CommonModal from './../../components/CommonModal/index.jsx';
import PresetTemplate from './../../components/PresetTemplate/index.jsx';
import {vendorsDanger as danger, vendorsGetUrlParam as getUrlParam, vendorsSuccess as success} from '../../utils/config'
import App from "../../layout/App";
import Switch from 'bee-switch';
import 'bee-switch/build/Switch.css';
let newArray;
export default class WorkQuality extends Component{
    onUseBtnClick = () => {
        newArray = [];
        queryWorktpl({billType: 1}).then((res) => {
            let data = res.data.result;
            this.setState({
                showUsetepModal: true,
                size: 'lg',
                modalContent: <PresetTemplate inherData={data} savePkType={this.savePkType}
                                              qualityTmpFlag='true'></PresetTemplate>,
                oneButton: true,
                showDisabled: false,
            });
        })
    };
    getData = (data) => {
        for (let i = 0; i < data.length; i++) {
            let item = data[i];
            if (item.checktype == 0) {
                item.checktype = '一般检查'
            } else if (item.checktype == 1) {
                item.checktype='现场验收'
            } else if (item.checktype == 2) {
                item.checktype = '平行检验'
            } else if (item.checktype == 3) {
                item.checktype = '旁站检查 '
            } else if (item.checktype == 5) {
                item.checktype = '综合验收 '
            } else if (item.checktype == 6) {
                item.checktype = '开工条件'
            } else {
                item.checktype = '巡查'
            }
        }
        return data
    };
    componentDidMount(){
        let url=window.location.href;
        let param=getUrlParam(url);
        if (param.start){
            let {start,size}=param;
            let pageIndex=start/size+1;
            this.setState({ pageInfo:{
                totalPages:'',
                pageIndex,
                pageSize:10,
                pageValue:1
            }},()=>{
                this.getWorkQualityDate({start,size})
            });
        }else {
            this.getWorkQualityDate({})
        }
    }
    getWorkQualityDate=(param)=>{
        let start=this.state.pageInfo.pageIndex;
        let size=this.state.pageInfo.pageSize;
        let defaultParam={
            keyword:'',
            start:(start-1)*size,
            size,
            ieStamp:new Date().getTime(),
            isAjax:1
        };
        param={...defaultParam,...param,status: this.state.showDisabled ? 2 : 1};
        getWorkQualityDateUrl(param).then((res)=>{
            let data=res.data;
            if (data.resultCode !=='busi_ex'){
                if (!data.result.result){
                    data.result.result=[]
                }
                let totalPages=Math.ceil(data.result.total/10);
                let gData=this.getData(data.result.result);
                this.setState({data:gData,
                    pageInfo:{...this.state.pageInfo,totalPages}})
            } else {
                danger({'text':data.exMsg})
            }
        })
    };

    constructor(props) {
        super(props);
        let _me = this;
        this.state = {
            key: '',
            usedModal: false,
            showDeleteModal: false,
            showUsetepModal: false,
            searchValue: '',
            chooseItemIndex: null,
            deleteChooseItem: null,
            data: [],
            size: '',
            PkTypeArray: [],
            oneButton: false,
            modalContent: '',
            focusColor: '',
            pageInfo: {
                totalPages: '',
                pageIndex: 1,
                pageSize: 10,
                pageValue: 1
            },
            columns: [
                {title: "名称", dataIndex: "checkname", key: "checkname", width: '300px',
                    render(text, rec, index) {
                        return (
                            <span className="quality__tableList_title" onClick={(e) => _me.handleRowClick(e, rec)}>{text}</span>
                        )
                    }
                },
                {title: "类别", dataIndex: "checktype", key: "checktype", width: '200px'},
                {title: "工序", dataIndex: "procedurename", key: "procedurename", width: '400px'},
                {title: "检查项", dataIndex: "itemcount", key: "itemcount", width: '100px'},
                {title: "操作", dataIndex: "operator", key: "operator", width: '200px',
                    render(text, rec, index) {
                        return (
                            <div>
                                {rec.enableStatus ?
                                <div style={{display:'inline-block'}}>
                                    <span className="quality__tableList_edit" onClick={(e) => _me.onEditAction(e, rec)}>编辑</span>
                                    <span className="quality__tableList_upright">|</span>
                                    <Popconfirm 
                                        content="您确认删除所选数据吗?"
                                        placement="left"
                                        onClose={_me.onDeleteTableItem(rec)}>
                                        <span className="quality__tableList_del">删除</span>
                                    </Popconfirm>
                                    <span className="quality__tableList_upright">|</span>
                                </div>
                                :''
                                }
                                <Popconfirm
                                    content={`您确定${rec.enableStatus ? '停用' : '启用'}所选数据吗?`}
                                    placement="left"
                                    onClose={_me.ontoggleStatus.bind(_me, rec, index)}>
                                    <span className="quality__tableList_del">{rec.enableStatus ? '停用' : '启用'}</span>
                                </Popconfirm>
                            </div>
                        )
                    }
                }
            ]
        };
    }
    handleSearch=(e)=>{
        this.setState({
            searchValue:e.target.value
        })
    };
    handleSearchSubmit=(notRequireKeyword)=>{
        let keyword=this.state.searchValue;
        let reg = /^\s*$/;
        if (reg.test(keyword)&&!notRequireKeyword){
            danger({'text':'请输入关键字再搜索！'});
        }else {
            this.setState({
                pageInfo:{
                    totalPages:'',
                    pageIndex:1,
                    pageSize:10,
                    pageValue:1
                }
            },()=>{
                this.searchAjax(keyword)
            })
        }
    };
    searchAjax=(keyword)=>{
        let start=this.state.pageInfo.pageIndex;
        let size=this.state.pageInfo.pageSize;
        let param={
            keyword,
            start:(start-1)*size,
            size,
            ieStamp:new Date().getTime(),
            isAjax:1,
            status: this.state.showDisabled ? 2 : 1
        };
        getWorkQualityDateUrl(param).then((res)=>{
            let data=res.data;
            if (data.resultCode !=='busi_ex'){
                if (!data.result.result){
                    data.result.result=[];
                    danger({'text':'没有找到符合的信息！'})
                }
                let totalPages=Math.ceil(data.result.total/10);
                let gData=this.getData(data.result.result);
                this.setState({data:gData,
                    pageInfo:{...this.state.pageInfo,totalPages}})
            } else {
                danger({'text':data.exMsg})
            }
        })
    };
    checkItem = (e, text, rec, index) => {
        e.stopPropagation();
        this.setState({
                chooseItemIndex: index,
                deleteChooseItem: rec,
                key:rec.key
            });
    };
    handleSelect=(index)=>{
        this.setState({
            pageInfo:{
                ...this.state.pageInfo,
                pageIndex:index,
            }},()=>{
            let keyword=this.state.searchValue;
            if(keyword){
                this.searchAjax(keyword)
            }else {
                this.getWorkQualityDate({})
            }
        })
    };
    onDeleteModalClose=()=>{
        this.setState({
            showDeleteModal: false
        });
    };
    onUsedModalClose=()=>{
        this.setState({
            usedModal: false
        });
    };
    onOpenModalClose=()=>{
        if (this.state.chooseItemIndex!=null){
            let deleteChooseItem=this.state.deleteChooseItem;
            if (deleteChooseItem.used){
                this.setState({
                    usedModal: true,
                });
            }else{
                this.setState({
                    showDeleteModal: true
                });
            }
        }else {
            danger({text:'请先选中具体信息再执行该操作！'});
        }
    };
    closeUsedModal=()=>{
        this.setState({
            usedModal: false,
        });
    };
    //删除选中行
    onDeleteTableItem = rec => {
       return () => {
        let deleteChooseItem = rec;
        this.getWorkQualityDeleteDate({...deleteChooseItem,ieStamp:new Date().getTime(),isAjax:1})
       }
    };
    ontoggleStatus = (rec, index) => {
        let _me = this;
        let oprflag = rec.enableStatus;
        toggleStatus({ ...rec, 'isAjax': 1, 'ieStamp': new Date().getTime() })
            .then(function (res) {
                if (res.data.resultCode != 'busi_ex') {
                    if (!_me.state.showDisabled && oprflag) {
                        _me.state.data.splice(index,1);
                    }else{
                        Object.assign(_me.state.data[index], res.data.result)
                    }
                    _me.setState({
                        data: _me.state.data
                    })
                } else {
                    danger({ 'text': res.data.exMsg })
                }
            })
    }
    getWorkQualityDeleteDate=(param)=>{
        getWorkQualityDeleteDateUrl(param).then((res)=>{
            let data=res.data;
            if (data.resultCode !=='busi_ex'){
                success({'text':'删除成功'});
                this.setState({
                    chooseItemIndex:null
                });
                this.getWorkQualityDate({})
            } else {
                danger({'text':data.exMsg})
            }
        })
    };
    onEditAction = (e, rec) => {
        let _me = this;
        //阻止渲染table时执行自定义单元格中绑定的onclick方法
        e.stopPropagation();
        let key = rec.key;
        let size = _me.state.pageInfo.pageSize;
        let start = (_me.state.pageInfo.pageIndex - 1) * size;
        window.location.href = `/workqualityedit.html?key=${key}&start=${start}&size=${size}`;

        // referCheck({ ...rec, 'isAjax': 1, 'ieStamp': new Date().getTime() })
        //     .then(function (res) {
        //         if (res.data.resultCode != 'busi_ex') {

        //         } else {
        //             danger({ 'text': res.data.exMsg })
        //         }
        //     })
    };
    handleBuild=()=>{
        let size=this.state.pageInfo.pageSize;
        let start=(this.state.pageInfo.pageIndex-1)*size;
        window.location.href=`/workqualitynewbuild.html?start=${start}&size=${size}`
    };
    handleRowClick=(e, rec)=>{
        e.stopPropagation();
        let size=this.state.pageInfo.pageSize;
        let start=(this.state.pageInfo.pageIndex-1)*size;
        let key=rec.key;
        window.location.href=`/workqualityitem.html?key=${key}&start=${start}&size=${size}`
    };
    handleFocus=()=>{
        this.setState({focusColor:'focus_color'})
    };
    handleBlur=()=>{
        this.setState({focusColor:''})
    };
    hideModal = () => {
        this.setState({
            showUsetepModal: false,
        });
    }
    savePkType = (key) => {
        let statusJson = this.findInArr(newArray, key);
        if (statusJson.status) {
            newArray.splice(statusJson.index, 1);
        } else {
            newArray.push(key);
        }
        this.setState({
            PkTypeArray: newArray
        });
    }
    findInArr = (arr, key) => {
        for (var i = 0; i < arr.length; i++) {
            if (arr[i] === key) {
                return {status: true, index: i};
            }
        }
        return {status: false};
    };
    handlerChooseAddTpl = () => {
        let _me = this;
        addWorktpl(this.state.PkTypeArray).then((res) => {
            let data = res.data;
            if (data.resultCode === 'busi_ex') {
                danger({text: data.exCode + data.exMsg});
                danger({text: '引用模版与现有档案存在名称或编码重复，请修改现有档案之后再做引用导入:  ' + data.exCode + ' ' + data.exMsg})
            } else {
                location.reload();
                this.setState({
                    showUsetepModal: false
                });
            }
        })
    }
    handleClearInput = () => {
        let _me = this;
        _me.setState({
            searchValue: ''
        });
    }
    onShowDisabledChange = () => {
		this.setState({
			showDisabled: !this.state.showDisabled
		},()=>{
			this.handleSearchSubmit(true);
		});
	}
    render(){
        return (
            <App>
            <div className='quality-container'>
                <div className='quality__header clearfix'>
                    <h4 >质量标准</h4>
                    <label className="quality__header_search_label">搜索 :</label>
                    <FormControl type="text"
                                 placeholder='请输入标准名称 或 工序名称'
                                 className='quality__search'
                                 onChange={this.handleSearch}
                                 onFocus={this.handleFocus}
                                 onBlur={this.handleBlur}
                                 value={this.state.searchValue}
                    />
                    <span className="clear-input-content" onClick={this.handleClearInput}>x</span>
                    <Button className={this.state.focusColor+' '+'quality__btn' + ' ' + 'btn_style_format'}
                             onClick={this.handleSearchSubmit}>
                             <Icon type="uf-search-light-2"></Icon>
                    </Button>
                    <div className='quality__headerRight'>
                        <Button className='quality__btn usebtn' onClick={this.onUseBtnClick}>引入预置模板</Button>
                        <CommonModal show={this.state.showUsetepModal}
                                     cancel={this.hideModal}
                                     confirm={this.handlerChooseAddTpl}
                                     size={this.state.size}
                                     content={this.state.modalContent}
                                     oneButton={this.state.oneButton}
                                     oneButtonText='确定'
                                     backdrop={false}
                                     hide={this.hideModal}
                        />
                        {/* <Button className='quality__btn ' onClick={this.onOpenModalClose}>删除</Button> */}
                        <CommonModal show={this.state.showDeleteModal}
                                     cancel={this.onDeleteModalClose}
                                     confirm={this.onDeleteTableItem}
                                     content={''}
                                     backdrop={false}
                                     bindCancel={true}
                        />
                        <CommonModal show={this.state.usedModal}
                                     cancel={this.onUsedModalClose}
                                     handlerConfirm={this.closeUsedModal}
                                     content={'该信息被引用无法删除'}
                                     backdrop={false}
                        />
                        {/* <Button className='quality__btn quality__btn--fontColor' colors="primary" onClick={this.onEditAction}>编辑</Button> */}
                        <Button className='quality__btn quality__btn--fontColor' colors="primary" onClick={this.handleBuild}>创建</Button>
                    </div>
                </div>
                <div className='quality__table clearfix'>
                    <div className="status_filter">
                        <Switch
                            checked={this.state.showDisabled}
                            onChange={this.onShowDisabledChange}
                            // className=""
                            size='sm'
                        />
                        <span className='showdisabletext'>显示停用</span>
                    </div>
                    <div className='quality__tableList'>
                        <Table
                            columns={this.state.columns}
                            data={this.state.data}
                            emptyText={() => '暂无数据'}
                        />
                    </div>
                    <div className='quality__pagination clearfix'>
                            < Pagination
                                first
                                last
                                prev
                                next
                                boundaryLinks
                                maxButtons={5}
                                items={this.state.pageInfo.totalPages}
                                activePage={this.state.pageInfo.pageIndex}
                                onSelect={this.handleSelect}
                            />
                        </div>
                </div>
            </div>
            </App>
        )
    }
}
